package com.api;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.pojo.MovieList;
import com.pojo.Room;
import com.service.DyService;
import com.service.RoomService;
import com.util.PortUtil;
import com.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/testDy")
public class DyTestAction {

    @Autowired
    private DyService dyService;

    @Autowired
    private RoomService roomService;

    private RedisTemplate redisTemplate;

    @Value("${server.url}")
    private String server;

    @Value("${server.port}")
    private String port;

    @Value("${dy.home}")
    private String home;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * @param dyid 电影编号
     * @return 200成功，404电影不存在
     */
    @RequestMapping("/dy/getDyDetail")
    public ResponseBean getDyDetail(long dyid) {

        MovieList dy = dyService.getById(dyid);
        if (dy == null) {
            return new ResponseBean(404, "电影不存在", null);
        }

        String ip = server;
        InputStream is = null;
        String tempPort = port;
        if (PortUtil.checkPortIsOpen(8090))
        {
            tempPort = "8090";
        }
        try {
            is = new FileInputStream("ip.properties");
            Properties p = new Properties();
            p.load(is);
            String ip2 = p.getProperty("server.ip");
            if (StringUtils.isEmpty(ip2) == false) {
                ip = "http://" + ip2 + ":" + tempPort + "/";
            }

        } catch (Exception e) {

        } finally {
            try {
                is.close();
            } catch (IOException e) {
                // e.printStackTrace();
            }
        }
        if (ip.endsWith("/")) {
            ip = ip.substring(0, ip.length() - 1);
        }
        String bigImage = dy.getBig_poster();
        String smallImage = dy.getLittle_poster();
        if (bigImage != null && bigImage.startsWith("http://") == false) {
            dy.setBig_poster(ip + bigImage);
        }
        if (smallImage != null && smallImage.startsWith("http://") == false) {
            dy.setLittle_poster(ip + smallImage);
        }
        String local_img = dy.getLocal_img();
        if (local_img != null) {
            File localImgFile = new File(home + "images/", local_img);
            if (localImgFile.exists()) {
                dy.setBig_poster(ip + "/images/" + local_img);
                dy.setLittle_poster(ip + "/images/" + local_img);
            }
        }

        String playUrl = ip+"/dy/"+dy.getMd5();
        dy.setPlay_url(playUrl);

        return new ResponseBean(200, "获取电影详情成功", dy);
    }

    /**
     * 根据电影类型查找电影
     *
     * @param typeid
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/dy/getDyByType")
    public ResponseBean getDyByType(Long typeid, String name, @RequestParam(defaultValue = "1") int page,
                                    @RequestParam(defaultValue = "10") int size) {
        if (typeid == null && name==null) {
            return new ResponseBean(404, "缺少参数", null);
        }

        String tempPort = port;
        if (PortUtil.checkPortIsOpen(8090))
        {
            tempPort = "8090";
        }

        String ip = server;
        InputStream is = null;
        try {
            is = new FileInputStream("ip.properties");
            Properties p = new Properties();
            p.load(is);
            String ip2 = p.getProperty("server.ip");
            if (StringUtils.isEmpty(ip2) == false) {
                ip = "http://" + ip2 + ":" + tempPort + "/";
            }

        } catch (Exception e) {

        } finally {
            try {
                is.close();
            } catch (IOException e) {
                // e.printStackTrace();
            }
        }
        if (ip.endsWith("/")) {
            ip = ip.substring(0, ip.length() - 1);
        }


        IPage result = dyService.page(page, size, typeid,name);
        long count = result.getTotal();
        List<MovieList> list = result.getRecords();
        for (MovieList m : list) {
            String bigImage = m.getBig_poster();
            String smallImage = m.getLittle_poster();
            if (bigImage != null && bigImage.startsWith("http://") == false) {
                m.setBig_poster(ip + bigImage);
            }
            if (smallImage != null && smallImage.startsWith("http://") == false) {
                m.setLittle_poster(ip + smallImage);
            }
            String local_img = m.getLocal_img();
            if (local_img != null) {
                File localImgFile = new File(home + "images/", local_img);
                if (localImgFile.exists()) {
                    m.setBig_poster(ip + "/images/" + local_img);
                    m.setLittle_poster(ip + "/images/" + local_img);
                }
            }

            String playUrl = ip+"/dy/"+m.getMd5();
            m.setPlay_url(playUrl);
        }
        return new ResponseBean(200, count, result.getRecords());
    }

    /**
     * 根据拼音搜索电影
     *
     * @param pinyin
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/dy/search")
    public ResponseBean search(String pinyin, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size) {
        IPage result = dyService.search(pinyin, page, size);
        if (result.getTotal() == 0) {
            return new ResponseBean(404, "没有找到相关电影", null);
        }
        String tempPort = port;
        if (PortUtil.checkPortIsOpen(8090))
        {
            tempPort = "8090";
        }
        String ip = server;
        InputStream is = null;
        try {
            is = new FileInputStream("ip.properties");
            Properties p = new Properties();
            p.load(is);
            String ip2 = p.getProperty("server.ip");
            if (StringUtils.isEmpty(ip2) == false) {
                ip = "http://" + ip2 + ":" + tempPort + "/";
            }

        } catch (Exception e) {

        } finally {
            try {
                is.close();
            } catch (IOException e) {
                // e.printStackTrace();
            }
        }
        if (ip.endsWith("/")) {
            ip = ip.substring(0, ip.length() - 1);
        }

        List<MovieList> list = result.getRecords();
        for (MovieList m : list) {
            String bigImage = m.getBig_poster();
            String smallImage = m.getLittle_poster();
            if (bigImage != null && bigImage.startsWith("http://") == false) {
                m.setBig_poster(ip + bigImage);
            }
            if (smallImage != null && smallImage.startsWith("http://") == false) {
                m.setLittle_poster(ip + smallImage);
            }
            String local_img = m.getLocal_img();
            if (local_img != null) {
                File localImgFile = new File(home + "images/", local_img);
                if (localImgFile.exists()) {
                    m.setBig_poster(ip + "/images/" + local_img);
                    m.setLittle_poster(ip + "/images/" + local_img);
                }
            }
            String playUrl = ip+"/dy/"+m.getMd5();
            m.setPlay_url(playUrl);
        }
        return new ResponseBean(200, result.getTotal(), result.getRecords());
    }

    /**
     * 根据拼音搜索电影
     *
     * @param dyid
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/dy/tuijian")
    public ResponseBean tuijian(int dyid, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "30") int size) {
        IPage result = dyService.tuijian(dyid, page, size);
        if (result.getTotal() == 0) {
            return new ResponseBean(404, "没有找到相关电影", null);
        }
        String tempPort = port;
        if (PortUtil.checkPortIsOpen(8090))
        {
            tempPort = "8090";
        }
        String ip = server;
        InputStream is = null;
        try {
            is = new FileInputStream("ip.properties");
            Properties p = new Properties();
            p.load(is);
            String ip2 = p.getProperty("server.ip");
            if (StringUtils.isEmpty(ip2) == false) {
                ip = "http://" + ip2 + ":" + tempPort + "/";
            }

        } catch (Exception e) {

        } finally {
            try {
                is.close();
            } catch (IOException e) {
                // e.printStackTrace();
            }
        }
        if (ip.endsWith("/")) {
            ip = ip.substring(0, ip.length() - 1);
        }

        List<MovieList> list = result.getRecords();
        for (MovieList m : list) {
            String bigImage = m.getBig_poster();
            String smallImage = m.getLittle_poster();
            if (bigImage != null && bigImage.startsWith("http://") == false) {
                m.setBig_poster(ip + bigImage);
            }
            if (smallImage != null && smallImage.startsWith("http://") == false) {
                m.setLittle_poster(ip + smallImage);
            }
            String local_img = m.getLocal_img();
            if (local_img != null) {
                File localImgFile = new File(home + "images/", local_img);
                if (localImgFile.exists()) {
                    m.setBig_poster(ip + "/images/" + local_img);
                    m.setLittle_poster(ip + "/images/" + local_img);
                }
            }
            String playUrl = ip+"/dy/"+m.getMd5();
            m.setPlay_url(playUrl);
        }
        return new ResponseBean(200, result.getTotal(), result.getRecords());
    }

    /**
     * @param mac
     * @return
     */
    @RequestMapping("/getSystemInfo")
    public ResponseBean getSystemInfo(String mac) {
        if (redisTemplate == null) {
            redisTemplate = (RedisTemplate) applicationContext.getBean("StringRedisTemplate");
        }
        //房间号
        QueryWrapper q = new QueryWrapper();
        q.eq("mac", mac);
        Map map = new HashMap();
        Room m = roomService.getRoomByMac(mac);
        if (m != null) {
            map.put("room", m.getRoom());
        }


        //版本过期时间
        Long daoqi = (Long) redisTemplate.boundValueOps("local_expire").get();
        if (daoqi != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            String riqi = sdf.format(new Date(daoqi));
            map.put("daoqi", riqi);
        }


        //跑马字
        try {
            InputStream is = new FileInputStream("pmz.properties");
            Properties p = new Properties();
            p.load(is);
            String pmz = p.getProperty("pmz");
            pmz = new String(pmz.getBytes("iso8859-1"), "utf-8");
            map.put("paoma", pmz);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            //return new ResponseBean(404,"获取失败",null);
        }


        String banquan = (String) redisTemplate.boundValueOps("copyright_image").get();
        String logo = (String) redisTemplate.boundValueOps("copyright_logo").get();
        String welcomeImg = (String) redisTemplate.boundValueOps("welcomeImg").get();
        if (banquan != null) {
            banquan = banquan.replaceAll("\"", "");
            if (banquan.startsWith("/")) {
                banquan = banquan.substring(1);
            }
            banquan = server + banquan;

        }

        if (logo != null) {
            logo = logo.replaceAll("\"", "");
            if (logo.startsWith("/")) {
                logo = logo.substring(1);
            }
            logo = server + logo;
        }

        if (welcomeImg != null) {
            welcomeImg = welcomeImg.replaceAll("\"", "");
            if (welcomeImg.startsWith("/")) {
                welcomeImg = welcomeImg.substring(1);
            }
            String downloadUrl = server + welcomeImg;
            File file = new File(home + "images/welcome");
            if (file.exists() == false) {
                file.mkdir();
            }
            int index = welcomeImg.lastIndexOf("/");
            String filename = welcomeImg.substring(index + 1);

            File welcomeImage = new File(home + "images/welcome/" + filename);
            if (welcomeImage.exists() == false) {
                try {
                    HttpUtil.downloadFile(downloadUrl, welcomeImage);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            String ip = null;
            InputStream is = null;
            try {
                is = new FileInputStream("ip.properties");
                Properties p = new Properties();
                p.load(is);
                String ip2 = p.getProperty("server.ip");
                if (StringUtils.isEmpty(ip2) == false) {
                    ip = "http://" + ip2 + ":" + port + "/";
                }

            } catch (Exception e) {
                return new ResponseBean(500, "IP未配置", null);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                }
            }
            if (ip != null && ip.endsWith("/")) {
                ip = ip.substring(0, ip.length() - 1);
            }
            if (welcomeImage.exists()) {

                String welcomeImgUrl = ip + "/images/welcome/" + filename;
                map.put("welcomeImg", welcomeImgUrl);
            }
        }else{
            String welcomeImgUrl = server + "upload/welcome/dy_welcome.png";
            map.put("welcomeImg", welcomeImgUrl);
        }

        //欢迎界welcomeImg


        map.put("banquan", banquan);
        map.put("logo", logo);

        return new ResponseBean(200, "获取成功", map);


    }


}
